package com.yearno.common.utils

import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.view.animation.Transformation
import androidx.core.view.isVisible
import androidx.interpolator.view.animation.FastOutLinearInInterpolator


enum class AnimUtil {

    INSTANCE;

    /**
     * 旋转一圈的动画
     *
     * @param fromDegrees
     * @param toDegrees
     * @param durationMillis
     * @return
     */
    fun getRotateAnimation(
        fromDegrees: Float,
        toDegrees: Float, durationMillis: Int
    ): Animation {
        val rotate = RotateAnimation(
            fromDegrees, toDegrees,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f
        )
        rotate.duration = durationMillis.toLong()
        rotate.fillAfter = true
        return rotate
    }

    /**
     * 控件展开显示动画
     */
    fun expand(view: View) {
        view.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val viewHeight: Int = view.measuredHeight
        view.layoutParams.height = 0
        val animation: Animation = object : Animation() {
            override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
                if (interpolatedTime == 1f) {
                    view.layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
                } else {
                    view.layoutParams.height = (viewHeight * interpolatedTime).toInt()
                }
                view.requestLayout()
                if (!view.isVisible && view.layoutParams.height > 0.1) {
                    view.visibility = View.VISIBLE
                }
            }
        }
        animation.duration = 300
        animation.interpolator = FastOutLinearInInterpolator()
        view.startAnimation(animation)
    }

    /**
     * 控件折叠收起隐藏
     */
    fun collapse(view: View) {
        view.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        val viewHeight: Int = view.measuredHeight
        val animation: Animation = object : Animation() {
            override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
                if (interpolatedTime == 1f) {
                    view.visibility = View.GONE
                } else {
                    view.layoutParams.height =
                        viewHeight - (viewHeight * interpolatedTime).toInt()
                    view.requestLayout()
                }
            }
        }
        animation.duration = 300
        animation.interpolator = FastOutLinearInInterpolator()
        view.startAnimation(animation)
    }
}